package com.coldworks.base.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.os.Build;
import android.telephony.TelephonyManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.manager.BasePrefManager;
import com.coldworks.base.manager.BaseStorageManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.base.util.BaseLoggerFactory;

/**
 * 异步任务，提交错误信息 前提是打开配置中的选项
 * 
 * @since 2012-03-23
 */
public class BaseLogReportTask extends Thread {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private Context ctx;
	private String versionName;
	private String url;

	public BaseLogReportTask(Context ctx, String versionName, String url) {
		this.ctx = ctx;
		this.versionName = versionName;
		this.url = url;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(BaseCONST.TASK.LOG_REPORT_SECOND * 1000);
		} catch (InterruptedException e) {
			return;
		}
		log.info("start reporting");
		// 检查配置是否允许提交错误信息
		if (BasePrefManager.getInstance().getBooleanFromPrefs(ctx,
				BaseCONST.KEY.DISABLE_DIAGNOSIS, false)) {
			log.info("user do not help");
			return;
		}
		// 检查是否要report
		if (BaseLoggerFactory.isLogReported()) {
			log.info("reported");
			return;
		}
		// 检查是否要report
		if (!BaseLoggerFactory.isLogReporting()) {
			log.info("cool!!!");
			return;
		}
		// 检查log文件是否存在
		File logerrfile = BaseStorageManager.getInstance().getLogErrFile();
		if (logerrfile == null || !logerrfile.exists()) {
			log.info("logerrfile not found");
			return;
		}
		BufferedReader reader = null;
		try {
			StringBuilder sb = new StringBuilder();
			reader = new BufferedReader(new FileReader(logerrfile));
			String line = reader.readLine();
			while (line != null) {
				sb.append(line);
				line = reader.readLine();
			}
			log.info("log reporting");

			TelephonyManager tManager = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			ConnectivityManager cm = (ConnectivityManager) ctx
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = cm.getActiveNetworkInfo();

			String networkOperator = tManager.getSimOperatorName()
					+ ";typeName=" + info.getTypeName() + ";networkType="
					+ tManager.getNetworkType() + ";host=" + Proxy.getHost(ctx)
					+ ";port=" + Proxy.getPort(ctx);

			Map<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("imei", tManager.getDeviceId());
			paramsMap.put("device_model", Build.MODEL + " " + Build.VERSION.SDK
					+ " " + Build.VERSION.RELEASE);
			paramsMap.put("network_operator", networkOperator);
			paramsMap.put("androidesk_version", versionName);
			paramsMap.put("android_version", Build.VERSION.RELEASE);
			paramsMap.put("internl_storage", String.valueOf(BaseStorageManager
					.getInstance().getInternalAvailableStore()));
			paramsMap.put("external_storage", String.valueOf(BaseStorageManager
					.getInstance().getSDAvailableStore()));
			paramsMap.put("log", sb.toString());

			BaseNetworkManager.getInstance().httpPOST(ctx, this.url, paramsMap);
		} catch (Exception e) {
			log.error("", e);
			return;
		} finally {
			BaseLoggerFactory.setLogReported();
			logerrfile.delete();
			log.info("succ");
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				log.error("", e);
			}
		}
	}
}
